#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netdb.h>
#include <errno.h>
#include <netinet/in.h>
#include <sys/socket.h>
 

extern int errno;

char gw_lookup[] = "mygateway.netradar.net";
char gw_file[] = "/.mygateway";

int main(void)
{
    struct hostent *hp;
    int error;
	char gw[40];
	char u_home[1024];
	char *tmp;

	FILE *fp;

	printf("\nLooking up nearest Phoebus Gateway...");

    /* resolve the domain name into a list of addresses */
    hp = gethostbyname(gw_lookup);
	
	if (!hp) {
		fprintf(stderr, "gateway lookup failed\n");
		exit(-1);
	}
	
	if (hp->h_addr_list[0]) {
		bzero(gw, 40);
		strcpy(gw, (char *)inet_ntoa(* (struct in_addr *)(hp->h_addr_list[0])));
		strcat(gw, "/5006");
		printf("%s\n", gw);
	}
	
	tmp = getenv("HOME");

	if (tmp) {
		bzero(u_home, 1024);
		strcat(u_home, tmp);
		strcat(u_home, gw_file);
	}
	
	printf("Saving gateway to %s\n", u_home);

	fp = fopen(u_home, "w");

	if (!fp) {
		perror("could not open file for writing\n");
		exit(-1);
	}
	else {
		fprintf(fp, gw);
		fprintf(fp, "\n");
	}
	
	printf("\nThis file may be modified to reflect a different gateway\n"
		   "choice to be used with the Phoebus client wrapper.  Running\n"
		   "this utility will overwrite the existing ~%s file!\n", gw_file);
	

	fclose(fp);

    return 0;
}
